package com.qn.example.controller;

import com.qn.example.utils.ValidateCodeUtils;
import com.qn.example.pojo.R;
import com.qn.example.pojo.User;
import com.qn.example.service.impl.UserServiceImpl;
import lombok.extern.slf4j.Slf4j;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.util.Enumeration;
import java.util.Map;
import java.util.concurrent.TimeUnit;

/**
 * @author 21276
 * @version 1.0
 * @date 2023/5/17 15:59
 */

@RestController
@RequestMapping("/user")
@Slf4j
public class UserController {

    @Resource
    private UserServiceImpl userService;

    @Resource
    private RedisTemplate redisTemplate;

    @PostMapping("/sendMsg")
    public R sendMsg(@RequestBody User user, HttpSession session) {
        //1. 生成随机验证码
        Integer verifyCode = ValidateCodeUtils.generateValidateCode(4);
        log.info("本次生成的验证码：" + verifyCode);
//        //2. 发送信息
//        SMSUtils.sendMessage("黑马旅游网","SMS_205126318",user.getPhone(),verifyCode);
        //3.  生成的验证码你需要保存到session
//        session.setAttribute("validateCode" + user.getPhone(), verifyCode);
        ValueOperations valueOperations = redisTemplate.opsForValue();
        valueOperations.set("verifyCode" + user.getPhone(), verifyCode, 30, TimeUnit.SECONDS); //设置多少分钟失效，验证码一般是1分钟失效
        return R.success("发送成功");
    }

    @PostMapping("/login")
    public R login(@RequestBody Map<String, String> param, HttpSession session) {
        //1. 取出客户提交手机号与验证码
        String phone = param.get("phone");
        String code = param.get("code");  //用户输入
        String validateCode = null;

        //从redis中获取验证码
        ValueOperations valueOperations = redisTemplate.opsForValue();
        try {
            validateCode = valueOperations.get("verifyCode" + phone).toString();
        } catch (Exception e) {
            e.printStackTrace();
            R.error("验证码已经过期");
        }

        //获取Session域中的code
//        try {
//            validateCode = session.getAttribute("validateCode" + phone).toString();
//
//        } catch (Exception e) {
//            e.printStackTrace();
//            return R.error("手机号和验证码不匹配");
//        }
        //3. 交给service去校验
        User user = userService.login(phone, code, validateCode);
        if (user != null) {
            //登录成功我需要在session中做一个登录成功标记
            session.setAttribute("user", user.getId());
            return R.success("登录成功");
        }
        return R.success("登录失败！");
    }

    //用于退出页面
    @PostMapping("/loginout")
    public void clear(HttpServletRequest request) {
        Enumeration<String> em = request.getSession().getAttributeNames();
        while (em.hasMoreElements()) { // 遍历枚举对象，逐个删除属性
            request.getSession().removeAttribute(em.nextElement());
        }
    }
}
